package com.robot.auth.service;

import com.robot.auth.entity.LoginUser;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:TODO
 * @author:qzg
 * @Date:2021-01-15 17:18
 */
@Component
@AllArgsConstructor
public class LogoutSuccessHandleImpl implements LogoutSuccessHandler {

    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        LoginUser loginUser = tokenService.getLoginUser(httpServletRequest);
        if(loginUser != null && loginUser.getToken() != null){
            tokenService.delLoginUser(loginUser.getToken());
        }
        String msg = "{\n    code:200\n    msg:退出登录成功！\n}";
        //renderString(httpServletResponse,msg);
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.getWriter().println(msg);
    }
}
